<template>
    <div class="container">
        <div class="nav">
            <el-breadcrumb :separator-icon="ArrowRight">
                <el-breadcrumb-item :to="{ path: '/control' }">主页</el-breadcrumb-item>
                <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="search">
            <h3>筛选条件</h3>
            <div class="search-details">
                <el-button type="danger" size="small">全部删除</el-button>
                <label>
                    <span>搜索：</span>
                    <el-input v-model="search.name" placeholder="请输入用户名" clearable size="small"></el-input>
                </label>
                <el-button class="float-right" size="small" @click="add('add')">新增</el-button>
            </div>
        </div>
        <hr>
        <el-config-provider :locale="zhCn" class="list">
            <el-table :data="pagesData" style="width: 100%" max-height="500px" @selection-change="changeId">
                <el-table-column type="selection" width="55" v-model="ids" />
                <el-table-column prop="user_name" label="用户昵称" width="100"></el-table-column>
                <el-table-column prop="sex" label="用户性别" width="100"></el-table-column>
                <el-table-column prop="birthday" label="用户生日" width="150"></el-table-column>
                <el-table-column prop="profession" label="用户职业" width="100"></el-table-column>
                <el-table-column prop="city" label="用户家乡" width="100"></el-table-column>
                <el-table-column prop="intro" label="简介签名" width="150"></el-table-column>
                <el-table-column prop="account" label="用户账号" width="125"></el-table-column>
                <el-table-column prop="password" label="用户密码" width="125"></el-table-column>
                <el-table-column prop="level" label="用户等级" width="80"></el-table-column>
                <el-table-column label="操作">
                    <template #default="scope">
                        <el-button type="primary" size="small" @click="add('edit', scope.row)">修改</el-button>
                        <el-button type="danger" size="small" @click="delproduct([scope.row.user_id])">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-config-provider>
        <div class="page">
            <el-config-provider :locale="zhCn">
                <el-pagination v-model:current-page="pages.current" :page-sizes="[5, 10, 15, 20]"
                    layout="total,sizes,prev, pager, next" :total="pages.pagetotal" v-model:page-size="pages.pagesize" />
            </el-config-provider>
        </div>
        <el-dialog v-model="visible" width="400px" @close="close()">
            <template #header>
                <div class="my-header">
                    <h4>{{ filed === "add" ? "新增用户信息" : "修改用户信息" }}</h4>
                    <el-form :rules="rules" :model="info" ref="formrules" label-width="100px">
                        <el-form-item label="用户昵称：" prop="user_name">
                            <el-input class="input" v-model="info.user_name" placeholder="请输入昵称" clearable size="small">
                            </el-input>
                        </el-form-item>
                        <el-form-item label="用户性别：" prop="sex">
                            <el-radio-group v-model="info.sex" class="ml-4">
                                <el-radio label="男" size="samll">男</el-radio>
                                <el-radio label="女" size="samll">女</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="用户生日：" prop="birthday">
                            <el-input class="input" v-model="info.birthday" placeholder="请输入生日" clearable size="small">
                            </el-input>
                        </el-form-item>
                        <el-form-item label="用户职业：" prop="profession">
                            <el-input class="input" v-model="info.profession" placeholder="请输入职业" clearable size="small">
                            </el-input>
                        </el-form-item>
                        <el-form-item label="用户家乡：" prop="city">
                            <el-input class="input" v-model="info.city" placeholder="请输入家乡" clearable size="small">
                            </el-input>
                        </el-form-item>
                        <el-form-item label="简介签名：" prop="intro">
                            <el-input class="input" v-model="info.intro" placeholder="请输入简介前面" clearable size="small">
                            </el-input>
                        </el-form-item>
                        <el-form-item label="用户账号：" prop="account">
                            <el-input class="input" v-model="info.account" placeholder="请输入账号" clearable size="small">
                            </el-input>
                        </el-form-item>
                        <el-form-item label="用户密码：" prop="password">
                            <el-input class="input" v-model="info.password" placeholder="请输入密码" clearable size="small">
                            </el-input>
                        </el-form-item>
                        <el-form-item label="等级：" prop="level">
                            <el-input-number v-model="info.level" :min="1" :max="99" :step="1" />
                        </el-form-item>
                    </el-form>
                    <div class="btn">
                        <el-button type="success" @click="changeProduct(formrules)">确定</el-button>
                    </div>
                </div>
            </template>
        </el-dialog>

        <el-dialog v-model="dialogVisible" title="提示" width="30%" :before-close="handleClose">
            <span>确定删除该用户信息吗?</span>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="ConfirmDelete"> 删除 </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>
    
<script setup>
import { computed, ref, onMounted } from "vue";
import zhCn from "element-plus/dist/locale/zh-cn.mjs";
import { ElMessage, ElMessageBox } from "element-plus";
import http from "../tools/axios";

const product = ref([]);
const d_id = ref();

const dialogVisible = ref(false);
const handleClose = () => {
    ElMessageBox.confirm("确定关闭这个弹窗吗?")
        .then(() => { })
        .catch(() => {
            // catch error
            dialogVisible.value = false;
        });
};
const ConfirmDelete = () => {
    dialogVisible.value = false;
     // 删除接口
    http.put("/user/delete", {
        "user_id": d_id.value
    }).then((res) => {
        getmsg();
    }).catch(err => {
        console.log(err);
    });
};
const catelist = ref([
    { id: 1, title: "电器" },
    { id: 2, title: "食品" },
    { id: 3, title: "餐具" },
    { id: 4, title: "洗涤剂" },
]);

const pages = ref({ current: 1, pagesize: 10, pagetotal: product.value.length });
const getmsg = () => {
    // 查询接口
    http.get("/user/user").then((res) => {
        product.value = res.data;
    });
};
getmsg();
const search = ref({ name: "", category: "" });
const searchData = computed(() => {
    let arr = product.value.filter((item) => {
        console.log(typeof (item.user_name));
        return (
            item.user_name.includes(search.value.name) &&
            (search.value.category ? item.pid === search.value.category : true)
        );
    });

    return JSON.parse(JSON.stringify(arr)).map((item) => {
        for (var i = 0; i < catelist.value.length; i++) {
            if (catelist.value[i].id === item.pid) {
                item.pid = catelist.value[i].title;
            }
        }
        return item;
    });
});
const pagesData = computed(() => {
    pages.value.pagetotal = searchData.value.length;
    const start = (pages.value.current - 1) * pages.value.pagesize;
    const end = pages.value.current * pages.value.pagesize;
    return searchData.value.slice(start, end);
});
const ids = ref([]);
const changeId = (value) => {
    ids.value = value.map((item) => {
        return item.id;
    });
    console.log(ids.value);
};
const delproduct = (id) => {
    dialogVisible.value = true;

    d_id.value = id;
   
};
const info = ref({});
const visible = ref(null);
const rules = ref({
    user_name: [{ required: true, message:'请输入用户昵称', trigger: "blur" }],
    sex: [{ required: true, message:'请选择性别', trigger: "blur" }],
    account: [{ required: true, message:'请输入用户账号',  trigger: "blur" }],
    password: [{ required: true, message:'请输入用户密码', trigger: "blur" }],
    level: [{ required: true, message:'请输入用户等级', trigger: "blur" }],
    // img: [
    //     {required: true, message: '请选择菜品图片', trigger: 'blur'}
    // ]
});
const formrules = ref(null);
const filed = ref("add");
const add = (str, obj) => {
    visible.value = true;
    filed.value = str;
    if (obj) {
        info.value = { ...obj };

    }
};
const close = () => {
    info.value = {};
};
const changeProduct = (formEl) => {
    if (!formEl) return;
    formEl.validate((valid, fields) => {
        if (valid) {
            if (filed.value === "add") {
                info.value.id = Date.now();
                product.value.unshift(info.value);
                // 新增接口
                http.post("/user/add", {
                    "user_name":info.value.user_name,
                    "sex":info.value.sex,
                    "birthday":info.value.birthday,
                    "profession":info.value.profession,
                    "city":info.value.city,
                    "intro":info.value.intro,
                    "account":info.value.account,
                    "level":info.value.level ,
                }).then((res) => {
                    if (res.code === 0) {
                        // 成功新增 刷新数据
                        // this.$router.go(0)
                        // 调用查询接口info
                        ElMessage({
                            showClose: true,
                            message: "添加成功",
                            type: "success",
                        });
                    }
                }).catch(err=>{
                    console.log(err);
                });
            } else {
                product.value = product.value.map((item) => {
                    if (item.user_id === info.value.id) {
                        console.log(info.value);
                        item = info.value;
                    }
                    return item;
                });
                // 调用修改接口
                // console.log(info.value.user_id);
                http.put("/user/update", {
                    "user_name":info.value.user_name,
                    "sex":info.value.sex,
                    "birthday":info.value.birthday,
                    "profession":info.value.profession,
                    "city":info.value.city,
                    "intro":info.value.intro,
                    "account":info.value.account,
                    "level":info.value.level ,
                    "user_id":info.value.user_id
                }).then((res) => {
                    if (res.code === 0) {
                        // 成功新增 刷新数据
                        // this.$router.go(0)
                        // 调用查询接口info
                        ElMessage({
                            showClose: true,
                            message: "修改成功",
                            type: "success",
                        });
                        getmsg();
                    }
                }).catch(err=>{
                    console.log(err);
                });
            }
            visible.value = false;
        } else {
            ElMessage({
                showClose: true,
                message: "请补全信息重新添加",
                type: "warning",
            });
        }
    });
};
const num = ref(1);
const handleChange = (value) => {
    console.log(value);
};
</script>
    
<style scoped>
.search-details {
    display: flex;
}

.search-details label {
    margin-left: 30px;
    color: #999;
}

label .el-input,
label .el-select {
    margin-left: 10px;
    width: 200px;
}

.float-right {
    margin-left: calc(100% - 480px);
}

label .el-select {
    margin-right: 30px;
}

.list .pic {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.page {
    display: flex;
    justify-content: end;
    margin: 20px 0;
}

.avatar-uploader {
    border: 1px solid #999;
    border-radius: 6px;
}

.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}

.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}

.btn {
    display: flex;
    justify-content: center;
}
</style>